var container;
var body;
var templateFile;



var variables = new Array();



function showValueOverrider(evt) {
	var chkbox = Event.findElement(evt);
	var defaultInput = chkbox.parentNode.previousSibling.firstChild;
	var overriderDiv = chkbox.parentNode.nextSibling.firstChild;

	if (chkbox.checked) {
		defaultInput.style.visibility = "hidden";
		overriderDiv.style.visibility = "visible";
	} else {
		defaultInput.style.visibility = "visible";
		overriderDiv.style.visibility = "hidden";
	}
}



function createVariableTableColumnTitle(tr, title, width) {
	var td = document.createElement("td");
	td.className = "column_title";
	td.style.width = width+"px";
	td.appendChild(document.createTextNode(title));
	tr.appendChild(td);
}

function createVariableTable() {

	var table = document.createElement("table");
	table.className = "content_table";
	var tbody = document.createElement("tbody");
	tbody.setAttribute("id", "variable-tbody");
	table.appendChild(tbody);
	container.appendChild(table);


	/* Header row*/
	var tr = document.createElement("tr");
	createVariableTableColumnTitle(tr, "Name", 80);
	createVariableTableColumnTitle(tr, "Default Value", 200);
	createVariableTableColumnTitle(tr, "", 20);
	createVariableTableColumnTitle(tr, "Override Value");
	tbody.appendChild(tr);

}


function addVariable(variableName, variableTypeName, defVal, usesMacro) {


	//Update array containing variable definitions
	variables.push({"name":variableName, "type":variableTypeName})



	var tr = document.createElement("tr");
	tr.setAttribute("id", "variable_"+variableName);




	/* Name */
	var td = document.createElement("td");
	td.appendChild(document.createTextNode(variableName));
	tr.appendChild(td);




	/* Default Value */
	var td = document.createElement("td");
	var inputField = document.createElement("input");
	inputField.value = (usesMacro ? usesMacro : defVal);
	inputField.disabled = true;
	inputField.style.width = "100%";
	td.appendChild(inputField);
	tr.appendChild(td);




	/* Override */
	var td = document.createElement("td");
	td.style.textAlign = "center";
	var chkbox = document.createElement("input");
	chkbox.setAttribute("type", "checkbox");
	chkbox.checked = false;
	td.appendChild(chkbox);
	tr.appendChild(td);





	/* Override value */
	var td = document.createElement("td");

	var initValue = defVal;
	var parent = document.createElement("div");
	parent.style.visibility = "hidden"; //Hide overrider initially


	//Check if this is an enumerable
	var enum = isEnum(variableTypeName);
	if (enum) {

		//Just present a selector
		var selector = document.createElement("select");

		for (var i=0; i<enum.length; i++) {
			selector.options[i] = new Option(enum[i], enum[i]);
		}

		parent.appendChild(selector);

		selectOption(selector, initValue);


	} else {

		var typeId = getTypeIdFromDisplayName(variableTypeName);

		if (typeId & TYPE_DATERANGE) {

			//Date Range
			addDateRange(parent, false, initValue);

		} else if (typeId & TYPE_DATE) {

			//Single Date
			addDate(parent, false, initValue);

		} else if ( (typeId & TYPE_INT) || (typeId & TYPE_FLOAT) || (typeId & TYPE_STRING) ) {

			//Primitive
			addPrimitive(parent, false, initValue);

		} else {

			//A user-defined type
			var selector = document.createElement("select");

			var values = fillType(typeId);
			var i=0;
			for (id in values) {
				selector.options[i] = new Option(values[id], id);
				i++;
			}
			parent.appendChild(selector);

			selectOption(selector, initValue);

		}
	}

	td.appendChild(parent);
	tr.appendChild(td);

	$("variable-tbody").appendChild(tr);

	Event.observe(chkbox, "click", showValueOverrider);
}




function runTemplate(evt) {

	var queryArgs = "";

	//Collect info overriden values
	for (var i=0; i<variables.length; i++) {
		var tr = $("variable_"+variables[i]["name"]);

		var variableName = variables[i]["name"];
		var typeName 	 = variables[i]["type"];
		var typeId    	 = getTypeIdFromDisplayName(typeName);
		var typeLabel 	 = typeLookup[typeId];
		if (!typeLabel) {
			//Enumerable, remove parantheses
			typeLabel = typeName.substring(1, typeName.length-1);
		}

		var currentNode = tr.childNodes[3].firstChild.firstChild;
		var chkbox = tr.childNodes[2].firstChild;
		if (chkbox.checked) {
			//Parse override value

			var value = null;

			if (typeId & TYPE_DATERANGE) {
				value = getDateRangeString(currentNode);

			} else if (typeId & TYPE_DATE) {
				value = getDateString(currentNode);

			} else if ( (typeId & TYPE_INT) || (typeId & TYPE_FLOAT) || (typeId & TYPE_STRING) ) {
				value = getPrimitiveString(currentNode);

			} else {

				//Enumerable or user-defined type
				var selector = currentNode;
				value = selector.options[selector.options.selectedIndex].value;
			}

			queryArgs += "&"+variableName+"="+value;

		}
	}

	window.location.href = "./?page=template_executor&run="+templateFile+"&do=1"+queryArgs;
}


function loadTemplate(filename) {

	new Ajax.Request("api_load_template.php?file="+filename, {
		method: 'get',
		onSuccess: function(transport) {
			renderTemplate(transport.responseXML);
		},
		onFailure: function(transport) {
		},
	});

}


function renderTemplate(xml) {

	var reportNode = xml.getElementsByTagName("template").item(0);

	//Set title
	$("report_title").appendChild(document.createTextNode(reportNode.getAttribute("title")));

	//Set description
	$("report_description").appendChild(document.createTextNode(reportNode.getElementsByTagName("meta").item(0).getElementsByTagName("description").item(0).firstChild.nodeValue.trim()));




	//Parse variables
	var vars = reportNode.getElementsByTagName("variable");
	for (var i=0; i<vars.length; i++) {
		var variableName      	= vars[i].getAttribute("name");
		var variableTypeLabel 	= vars[i].getAttribute("type");
		var variableTypeName 	= getTypeDisplayNameFromLabel(variableTypeLabel);
		if (!variableTypeName) {
			variableTypeName = "("+variableTypeLabel+")";  //Assume enumerable
		}

		var defVal 	= null;
		var usesMacro 	= false;

		if (vars[i].getAttribute("uses-macro")) {
			usesMacro = vars[i].getAttribute("uses-macro");
		} else {
			defVal = vars[i].firstChild.nodeValue.trim();
		}

		addVariable(variableName, variableTypeName, defVal, usesMacro);
	}

}



function createTitles() {
	var table = document.createElement("table");
	var tbody = document.createElement("tbody");
	table.appendChild(tbody);
	container.appendChild(table);


	var tr = document.createElement("tr");
	var td1 = document.createElement("td");
	var td2 = document.createElement("td");

	td1.style.fontWeight = "bold";
	td1.appendChild(document.createTextNode("Template title:"));

	td2.setAttribute("id", "report_title");

	tr.appendChild(td1);
	tr.appendChild(td2);
	tbody.appendChild(tr);


	var tr = document.createElement("tr");
	var td1 = document.createElement("td");
	var td2 = document.createElement("td");

	td1.style.fontWeight = "bold";
	td1.appendChild(document.createTextNode("Template description:"));

	td2.setAttribute("id", "report_description");

	tr.appendChild(td1);
	tr.appendChild(td2);
	tbody.appendChild(tr);

}


onload = function() {

	body = document.getElementsByTagName("body").item(0);
	container = $("main_container");


	createTitles();

	createVariableTable();


	var footerDiv = document.createElement("div");
	footerDiv.style.width 		= "100%";
	footerDiv.style.textAlign 	= "right";

	var runHref = document.createElement("a");
	runHref.href = "javascript:;";
	var runImg = document.createElement("img");
	runImg.src = "img/silk/report_go.png";
	runImg.style.border = "0px";
	runImg.style.marginRight = "6px";
	runHref.appendChild(runImg);
	runHref.appendChild(document.createTextNode("Run"));
	footerDiv.appendChild(runHref);

	container.appendChild(footerDiv);
	Event.observe(runHref, "click", runTemplate);


	//Has a previous template been requested?
	var paramName = "&template=";
	var paramIdx  = location.href.indexOf(paramName);
	if (paramIdx != -1) {
		var nextParamStart = location.href.indexOf("&", paramIdx+1);
		var paramStop = ( (nextParamStart==-1) ? location.href.length : nextParamStart);
		var paramValue = location.href.substring(paramIdx+paramName.length, paramStop);
		templateFile = paramValue;
		loadTemplate(templateFile);
	}


}

